package com.swak.frame.hystrix;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.swak.frame.command.annotation.ExtAsyncResult;
import com.swak.frame.dto.base.SysRestCode;
import com.swak.frame.dto.request.SwakRequest;
import com.swak.frame.dto.response.Responses;
import com.swak.frame.dto.response.RpcResponse;
import com.swak.frame.hystrix.annotation.SwakHystrix;

@Service
public class HystrixDemoServiceImpl implements HystrixDemoService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@SwakHystrix(fallbackMethod = "fallback", coreSize = 1, maximumSize = 1, maxQueueSize = 1)
	@Override
	public RpcResponse<String> hystrixDemo(SwakRequest request) {
		try {
			TimeUnit.SECONDS.sleep(20);
		} catch (InterruptedException e) {
			logger.error("hystrixDemo,message=" + e.getMessage(), e);
		}
		return Responses.buildResponse(request.getPin());
	}

	@SwakHystrix(fallbackMethod = "fallback", coreSize = 1, maximumSize = 1, maxQueueSize = 1)
	@Override
	public Future<RpcResponse<String>> hystrixDemoAsync(SwakRequest request) {
		return ExtAsyncResult.supplyAsync(() -> {
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				logger.error("hystrixDemoAsync,message=" + e.getMessage(), e);
			}
			return Responses.buildResponse(request.getPin());
		});
	}

	protected RpcResponse<String> fallback(SwakRequest request) {
		return Responses.buildResponse("fallback").of(SysRestCode.OPER_UPPER_LIMIT);
	}

	protected Future<RpcResponse<String>> fallbackAsync(SwakRequest request) {
		return ExtAsyncResult.supplyAsync(() -> Responses.buildResponse("fallback ayac").of(SysRestCode.SYS_REQ_LIMIT));
	}
}
